<template>
  <el-dialog
    v-dialogDrag
    :visible="popupsVisible"
    width="90%"
    :append-to-body="true"
    :close-on-click-modal="false"
    @close="closeEdit"
  >
    <dialogHeader slot="title" :title="titleName" :style-type="$store.state.app.dialogType" />
    <div
      v-loading="Dialoading"
      style="margin:1rem"
    >
      <!-- 显示按钮的onetabel -->
      <one-table-template
        ref="multipleTable"
        :dynamic-components="tableComponent"
        :dynamic-form-fields="formField"
        :dynamic-buttons="tableButtons"
        :dynamic-is-show-more-btn="false"
      />
    </div>
  </el-dialog>
</template>

<script>
import dialogHeader from '@/components/dialogHeader'
import OneTableTemplate from '@/components/templates/oneTable'
import { orgApis } from '@/api/vesalesapi.js'
export default {
  components: {
    dialogHeader,
    OneTableTemplate
  },
  props: {
    popupsVisible: {
      type: Boolean,
      default: false
    },
    dataForForm: {
      type: Object,
      default: () => {}
    }
  },
  data() {
    // 页面标识（与上面beforeRouteEnter中的对应）
    const viewPageCode = this.$route.path
    // 绑定事件配置化事件
    this.$ConfigCache.CacheConfig.bindEvent(this, [viewPageCode])
    return {
      Dialoading: false,
      titleName: '机动车销售统一发票',
      // 动态组件-按钮
      tableButtons:
        this.$ConfigCache.CacheConfig.cacheData[viewPageCode] &&
        this.$ConfigCache.CacheConfig.cacheData[viewPageCode].tableButtons &&
        this.$ConfigCache.CacheConfig.cacheData[viewPageCode].tableButtons
          .length > 0
          ? this.$ConfigCache.CacheConfig.cacheData[viewPageCode].tableButtons
          : [
            {
              compKey: 'btnKey1',
              type: 'primary',
              size: 'small',
              name: '',
              isShow: true,
              clickEvent: () => this.invoice(),
              text: '开票'
            },
            {
              compKey: 'btnKey2',
              type: '',
              size: 'small',
              isShow: true,
              icon: 'iconfont  icon-cancel',
              clickEvent: () => this.closeEdit(1),
              text: '取消'
            }
          ],
      // 动态组件-查询条件
      tableComponent: this.$ConfigCache.CacheConfig.cacheData[viewPageCode] &&
      this.$ConfigCache.CacheConfig.cacheData[viewPageCode].tableComponents.length > 0
        ? this.$ConfigCache.CacheConfig.cacheData[viewPageCode].tableComponents : [
          {
            ompKey: 'compKey1',
            labelName: '开票日期：',
            codeField: 'invoiceDate',
            component: () => import('@/components/org/commonInput'),
            type: 'inputText',
            isMust: true,
            disabled: true,
            span: 6
          },
          {
            compKey: 'compKey20',
            labelName: '开票人：',
            codeField: 'invoiceEmpName',
            component: () => import('@/components/org/commonInput'),
            type: 'inputText',
            isMust: true,
            disabled: true,
            span: 6
          },
          {
            compKey: 'compKey2',
            labelName: '发票代码：',
            codeField: 'invoiceCode',
            component: () => import('@/components/org/commonInput'),
            type: 'inputText',
            isMust: true,
            disabled: true,
            span: 6
          },
          {
            compKey: 'compKey3',
            labelName: '发票号码：',
            codeField: 'invoiceNo',
            component: () => import('@/components/org/commonInput'),
            type: 'inputText',
            isMust: true,
            disabled: true,
            span: 6
          },
          {
            compKey: 'compKey5',
            labelName: '购买方名称：',
            codeField: 'buyTypeName',
            component: () => import('@/components/org/commonInput'),
            type: 'inputText',
            isMust: true,
            disabled: true,
            span: 6
          },
          {
            compKey: 'compKey6',
            labelName: '身份证号码/组织机构代码：',
            codeField: 'signatoryIdCard',
            component: () => import('@/components/org/commonInput'),
            type: 'inputText',
            isMust: true,
            disabled: true,
            span: 6
          },
          {
            compKey: 'compKey21',
            labelName: '商品编码：',
            codeField: 'GOODS_CODE',
            component: () => import('@/components/org/commonInput'),
            type: 'inputText',
            isMust: true,
            disabled: true,
            span: 6
          },
          {
            compKey: 'compKey27',
            labelName: '厂牌型号：',
            codeField: 'factoryPlateModel',
            canInput: true,
            lookuptype: 'VE1347',
            component: () => import('@/components/org/LookupValue'),
            isRequire: true,
            type: 'dropdownList',
            isMust: true
          },
          {
            compKey: 'compKey9',
            labelName: '车型名称：',
            codeField: 'GOODS_NAME',
            component: () => import('@/components/org/commonInput'),
            type: 'inputText',
            isMust: true,
            disabled: true,
            span: 6
          },
          {
            compKey: 'compKey8',
            labelName: 'VIN码：',
            codeField: 'vin',
            component: () => import('@/components/org/commonInput'),
            type: 'inputText',
            isMust: true,
            disabled: true,
            span: 6
          },
          {
            compKey: 'compKey24',
            labelName: '发动机号码：',
            codeField: 'EngineNumber',
            canInput: true,
            isShow: true,
            component: () => import('@/components/org/commonInput'),
            isRequire: true,
            dataToObject: {
              maxLength: 20
            },
            type: 'inputText',
            disabled: false,
            isMust: true,
            span: 6
          },
          {
            compKey: 'compKey7',
            labelName: '合格证号：',
            isRequire: true,
            codeField: 'qualifiedCertNo',
            component: () => import('@/components/org/commonInput'),
            type: 'inputText',
            isMust: true,
            disabled: true,
            span: 6
          },
          {
            compKey: 'compKey26',
            labelName: '限乘人数：',
            canInput: true,
            codeField: 'LimitedNumber',
            component: () => import('@/components/org/commonInput'),
            isRequire: true,
            validrule: { isInteger: true },
            type: 'inputText',
            disabled: false,
            isMust: true,
            span: 6
          },
          {
            compKey: 'compKey25',
            labelName: '吨位：',
            codeField: 'tonnage',
            canInput: true,
            component: () => import('@/components/org/commonSelect'),
            oFields: 'statusId,statusText',
            options: [
              { statusId: '无', statusText: '无' },
              { statusId: '-', statusText: '-' }
            ],
            type: 'inputText',
            isMul: false,
            disabled: false,
            isMust: true,
            span: 6
          },
          {
            compKey: 'compKey22',
            labelName: '进口证明书号：',
            codeField: 'ImportCertificateNo',
            canInput: true,
            component: () => import('@/components/org/commonSelect'),
            oFields: 'statusId,statusText',
            options: [
              { statusId: '无', statusText: '无' },
              { statusId: '-', statusText: '-' }
            ],
            type: 'inputText',
            disabled: false,
            isMul: false,
            isMust: true,
            span: 6
          },
          {
            compKey: 'compKey23',
            labelName: '商检单号：',
            canInput: true,
            codeField: 'CommodityInspectionNo',
            component: () => import('@/components/org/commonSelect'),
            oFields: 'statusId,statusText',
            options: [
              { statusId: '无', statusText: '无' },
              { statusId: '-', statusText: '-' }
            ],
            type: 'inputText',
            isMul: false,
            disabled: false,
            isMust: true,
            span: 6
          },
          {
            compKey: 'compKey17',
            labelName: '增值税税率：',
            codeField: 'VatRate',
            component: () => import('@/components/org/commonInput'),
            type: 'inputText',
            isMust: true,
            disabled: true,
            span: 6
          },
          {
            compKey: 'compKey18',
            labelName: '增值税税额：',
            codeField: 'TaxAmount',
            component: () => import('@/components/org/commonInput'),
            type: 'inputText',
            isMust: true,
            disabled: true,
            span: 6
          },
          {
            compKey: 'compKey10',
            labelName: '税价合计：',
            codeField: 'invoiceAmoutL',
            component: () => import('@/components/org/commonInput'),
            type: 'inputText',
            isMust: true,
            disabled: true,
            span: 6
          },
          {
            compKey: 'compKey11',
            labelName: '小写：',
            codeField: 'invoiceAmout',
            component: () => import('@/components/org/commonInput'),
            type: 'inputText',
            isMust: true,
            disabled: true,
            span: 6
          },
          {
            compKey: 'compKey19',
            labelName: '不含税价：',
            codeField: 'PriceExcludingTax',
            component: () => import('@/components/org/commonInput'),
            type: 'inputText',
            isMust: true,
            disabled: true,
            span: 6
          },
          {
            compKey: 'compKey12',
            labelName: '销货单位名称：',
            codeField: 'dlrFullName',
            component: () => import('@/components/org/commonInput'),
            type: 'inputText',
            isMust: true,
            disabled: true,
            span: 6
          },
          {
            compKey: 'compKey14',
            labelName: '销货单位账号：',
            codeField: 'applicantBankAccount',
            component: () => import('@/components/org/commonInput'),
            type: 'inputText',
            isMust: true,
            disabled: true,
            span: 6
          },
          {
            compKey: 'compKey13',
            labelName: '销货单位电话：',
            codeField: 'custTel',
            component: () => import('@/components/org/commonInput'),
            type: 'inputText',
            isMust: true,
            disabled: true,
            span: 6
          },
          {
            compKey: 'compKey15',
            labelName: '销货单位地址：',
            codeField: 'applicantAddr',
            component: () => import('@/components/org/commonInput'),
            type: 'inputText',
            isMust: true,
            disabled: true,
            span: 6
          },
          {
            compKey: 'compKey16',
            labelName: '开户银行：',
            codeField: 'applicantBank',
            component: () => import('@/components/org/commonInput'),
            type: 'inputText',
            isMust: true,
            disabled: true,
            span: 6
          },
          {
            compKey: 'compKey44',
            labelName: '机动车新旧规范：',
            codeField: 'vehicleSpecificatio',
            canInput: true,
            lookuptype: 'VE1349',
            component: () => import('@/components/org/LookupValue'),
            isRequire: true,
            type: 'dropdownList',
            isMust: true
          },
          {
            compKey: 'compKey4',
            labelName: '税控码：',
            codeField: 'taxCtrlCode',
            component: () => import('@/components/org/commonInput'),
            type: 'inputText',
            isMust: true,
            disabled: true,
            span: 6
          }
        ],
      formField: {
        factoryPlateModel: '',
        vehicleSpecificatio: '',
        LimitedNumber: '',
        tonnage: '',
        EngineNumber: '',
        CommodityInspectionNo: '',
        ImportCertificateNo: '',
        invoiceDate: '',
        buyTypeName: '',
        signatoryIdCard: '',
        carType: '',
        GOODS_CODE: '',
        GOODS_NAME: '',
        brandModel: '',
        qualifiedCertNo: '',
        invoiceAmout: '',
        invoiceAmoutL: '',
        applicantName: '',
        custTel: '',
        applicantTax: '',
        applicantBankAccount: '',
        applicantAddr: '',
        applicantBank: '',
        VatRate: '',
        TaxAmount: '',
        PriceExcludingTax: '',
        weight: '',
        carConfigParaValue: '',
        invoiceEmpName: '',
        remark: '',
        invoiceCode: '',
        invoiceNo: '',
        taxCtrlCode: '',
        cardNo: '',
        engineNo: '',
        vin: ''
      }
    }
  },
  watch: {
    'popupsVisible': {
      handler(newVal) {
        const orderStatus = this.dataForForm.orderStatusName
        const checkRV = this.dataForForm.checkRV
        if (newVal) {
          // 订单状态 为已申请的才能够编辑 审核通过
          if (orderStatus !== '开票审核通过') {
            this.tableButtons.forEach(item => { item.isShow = false })
            this.tableComponent.forEach(item => {
              item.disabled = true
            })
          } else {
            this.tableButtons.forEach(item => { item.isShow = true })
            this.tableComponent.forEach(item => {
              if (item.codeField === 'EngineNumber' && checkRV === 'RV') {
                item.disabled = true
              } else {
                if (item.canInput) {
                  item.disabled = false
                } else {
                  item.disabled = true
                }
              }
            })
            this.formField.vehicleSpecificatio = '0'
          }
          this.queryform()
        } else {
          if (orderStatus === '开票审核通过') {
            this.formField.factoryPlateModel = ''
            this.formField.LimitedNumber = '5'
            this.formField.tonnage = ''
            this.formField.EngineNumber = ''
            this.formField.CommodityInspectionNo = ''
            this.formField.ImportCertificateNo = ''
            this.formField.vehicleSpecificatio = '0'
          }
        }
      },
      immediate: true,
      deep: true
    }
  },
  mounted() {

  },
  methods: {
    // 开票
    invoice() {
      this.$utils.validataMoth(this, 'validpage')
      if (this.valid) {
        this.Dialoading = true
        const {
          factoryPlateModel,
          LimitedNumber,
          tonnage,
          EngineNumber,
          CommodityInspectionNo,
          vehicleSpecificatio,
          ImportCertificateNo } = this.formField
        var queryid = {
          saleOrderId: this.dataForForm.saleOrderId,
          vin: this.dataForForm.vin,
          updateControlId: this.dataForForm.updateControlId,
          saleOrderCodeC: this.dataForForm.saleOrderCodeC,
          factoryPlateModel,
          vehicleSpecificatio,
          LimitedNumber,
          tonnage,
          EngineNumber,
          CommodityInspectionNo,
          ImportCertificateNo
        }
        // // 先读取参数中的传输对象
        const returnObj = {
        // api配置
          apiConfig: orgApis.orderinvoiceConfirm,
          // 条件/实体参数（变量），根据typeParam中的定义配置
          variables: queryid
        }
        // 转换了中台请求格式数据
        var paramD = this.$getParams(returnObj, null, this.dynamicApiStyle)
        // 调用中台API方法（可复用）
        this.$requestAPI(paramD, this.dynamicApiStyle).then(response => {
          this.Dialoading = false
          if (response.msg) {
            this.$message({
              message: response.msg,
              type: 'warn',
              uration: 2000
            })
          }
          if (response.result === '1') {
            this.closeEdit('1')
          }
        }).catch(err => {
          console.info(err)
        })
      }
    },
    // 关闭弹窗
    closeEdit(type) {
      this.$emit('close', type)
    },
    queryform() {
      this.Dialoading = true
      var queryid = { orderId: this.dataForForm.saleOrderId }
      // // 先读取参数中的传输对象
      const returnObj = {
      // api配置
        apiConfig: orgApis.orderinvoicedetailsQuery,
        // 条件/实体参数（变量），根据typeParam中的定义配置
        variables: queryid
      }
      // 转换了中台请求格式数据
      var paramD = this.$getParams(returnObj, null, this.dynamicApiStyle)
      // 调用中台API方法（可复用）
      this.$requestAPI(paramD, this.dynamicApiStyle).then(response => {
        this.Dialoading = false
        if (response.result === '0') {
          if (response.msg) {
            this.$message({
              message: response.msg,
              type: 'warn',
              uration: 2000
            })
          }
          return
        }
        // 返回json
        if (response.result === '1') {
          this.Dialoading = false
          Object.assign(this.formField, response.rows[0], response.rows[1])
          this.formField.invoiceAmoutL = this.$utils.DXZH(this.formField.invoiceAmout)
          if (this.formField.vehicleSpecificatio === null) {
            this.formField.vehicleSpecificatio = '0'
          }
          if (this.formField.LimitedNumber === null) {
            this.formField.LimitedNumber = '5'
          }
        }
      }).catch(err => {
        console.info(err)
      })
    }
  }
}
</script>
<style lang='scss' scoped>
  /deep/ .el-dialog{
    margin-top:5rem !important
  }
</style>
